package com.example.gulimall.cas.service.impl;

import com.example.gulimall.cas.dao.RoleDAO;
import com.example.gulimall.cas.dao.UserDAO;
import com.example.gulimall.cas.model.RoleDO;
import com.example.gulimall.cas.model.UserDO;
import com.example.gulimall.common.service.UserAuthService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>@description: security查找用户  </p>
 * <p>@author: JGD </p>
 * <p>@create: 2020/3/12 10:53 </p>
 * <p>@version : 2.0.0
 **/
@Service("userDetailsService")
public class UserDetailServiceImpl implements UserAuthService {
    @Resource
    private UserDAO userDAO;
    @Resource
    private RoleDAO roleDAO;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserDO user = userDAO.selectByUserName(username);
        return loadRole(user);
    }

    @Override
    public UserDetails loadUserByMobile(String mobile) {
        UserDO user = userDAO.selectByMobile(mobile);
        return loadRole(user);
    }

    /**
     * 加载角色
     * @param userDO 用户信息
     * @return UserDetails
     */
    private UserDetails loadRole(UserDO userDO) {
        List<RoleDO> roleList = roleDAO.selectByUserId(userDO.getId());
        List<GrantedAuthority> list = new ArrayList<>();
        for (RoleDO roleDO : roleList) {
            GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(roleDO.getEnname());
            list.add(grantedAuthority);
        }
        return new User(userDO.getUsername(), userDO.getPassword(), list);
    }
}
